/**
 * Created by 小敏哥 on 2017/11/27.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import {submitFormData} from '../../actions/homeAction';
import {confirmOrderInfo} from '../../actions/confirmOrderAction';
import BottomMenu from '../../../../../../src/js/components/bottomMenu';
import timeOutLocalStorage from '../../../../../js/utils/timeOutLocalStorage'
import AddressPicker from '../../components/home/addressPicker';
import DriverInputContent from '../../components/home/drivingLicense/InputContent';
import ProcessInstance from '../../components/home/ProcessInstance';
import style from './index.scss'
import common from "../../../../../js/utils/common";
import {Toast} from 'antd-mobile';

class Home extends Component {
    constructor(props) {
        super(props);
        this.address = {};
        this.data = {
            examCity: {value: null, check: false, error: '请选择考试城市'},//考试城市，provinceCode：省份编码，cityCode：城市编码，fullCity：城市名称
            //驾驶证邮寄
            driverName: {value: '', check: false, error: '请输入正确的驾驶人姓名'},//驾驶者姓名
            driverIdCard: {value: '', check: false, error: '请输入正确的身份证号'},//驾驶者身份证
        };//不同证件邮寄的区分配置
        this.canGo = false;//所有验证是否通过
        this.state = {
            initArea: [],
            agree: sessionStorage.getItem('isAgree')=='true'?true:false,
        };
    }


    componentDidMount() {
        common.setViewTitle('驾驶证邮寄');
    }

    componentWillUnmount() {
    }

    //底部跳转
    bottomHandle(index) {
        if (index == 0) {
            this.context.router.push('/');
        }
        else {
            this.context.router.push('orderList');
        }
    }

    //点击后修改同意状态
    setAgreeStatus() {
        this.setState({
            agree: !this.state.agree
        }, () => {
            sessionStorage.setItem('isAgree',this.state.agree?'true':'false');
            this.checkAllData();
        });
    }


    //缓存地址数据
    cacheAddress(data) {
        timeOutLocalStorage.setItem('sendIdCardAddress', data, 24 * 60 * 60 * 1000);
    }

    //检查所有数据是否正确
    checkAllData() {
        for (var index in this.data) {
            if (!this.data[index].check) {
                this.canGo = false;
                return;
            }
        }
        if (!this.props.currentAddress) {
            this.canGo = false;
            return;
        }
        this.canGo = true;
    }

    //检测异常数据
    checkDataAndShowMessage() {
        for (var index in this.data) {
            if (!this.data[index].check) {
                Toast.info(this.data[index].error, 2);
                return;
            }
        }
        if (!this.props.currentAddress) {
            Toast.info('请选择地址', 2);
        }
        if (!this.state.agree) {
            Toast.info('请阅读并同意《驾驶证邮寄服务协议》', 2);
            return;
        }
    }

    //提交数据
    submitData() {
        if (this.canGo&&this.state.agree) {
            let {
                driverName,
                driverIdCard,
                examCity,
            } = this.data;
            let {contactName, cellNum, fullAddr, provinceId, cityId, countyId,street} = this.props.currentAddress;
            //缓存数据给confirmOrder
            this.props.dispatch(confirmOrderInfo({
                idCard: driverIdCard.value,
                userName: driverName.value,
                examCity: examCity.value.fullCity,
                receiveName: contactName,
                receivePhone: cellNum,
                fullAddress: fullAddr,
            }));
            let apiObj = {
                'cardName': driverName.value,
                'cardNbr': driverIdCard.value,
                'certPlaceProvinceId': examCity.value.provinceCode,
                'certPlaceCityId': examCity.value.cityCode,
                'certPlaceName': examCity.value.fullCity,
                'address.contactName': contactName,
                'address.cellNum': cellNum,
                'address.provinceId': provinceId,
                'address.cityId': cityId,
                'address.countyId': countyId,
                'address.fullAddr': fullAddr,
                'address.street': street,

            };
            this.props.dispatch(submitFormData(apiObj, () => {
                //缓存请求数据，下个页面的接口需要使用
                sessionStorage.setItem('orderParameters', JSON.stringify(apiObj));
                this.context.router.push('confirmOrder');
            }));
        }
        else {
            this.checkDataAndShowMessage();
        }
    }

//设置输入框的值和检查状态
    setValue(valueType, value, check) {
        this.data[valueType].value = value;
        this.data[valueType].check = check;
        this.checkAllData();
    }

    //构建输入框
    structInputContent() {
        return <DriverInputContent driverIdCardCallBack={(value, check) => {
            this.setValue('driverIdCard', value, check);
        }} driverNameCallBack={(value, check) => {
            this.setValue('driverName', value, check);
        }} examCityCallBack={(value, check) => {
            this.setValue('examCity', value, check);
        }}/>
    }

    render() {
        return <div className={style.home}>
            <div className={style.headerMessage}>
                <img src="./images/bigDrivingLicense.png"/>
                <p>
                    填写驾驶证邮寄信息，当驾驶证出证后邮政速递人员将送证上门并收取快递费。如需咨询请联系020-11183。
                </p>
            </div>
            {this.structInputContent()}
            <p className={style.title}><img src="./images/Rectangle 2.png"/> <span>收件人信息</span></p>
            <img className={style.titleImg} src="./images/line.png"/>
            <AddressPicker/>

            <p className={style.title}><img src="./images/Rectangle 2.png"/> <span>办理流程</span></p>
            <ProcessInstance content={[{text: '通过驾驶证考试'}, {text: '在线填写邮寄信息并提交'}, {text: '公安部门审批、制证'}, {
                text: '邮政速递人员送证上门并收取服务费',
                tips: '如需邮费发票请向上门送证的邮政速递员索取'
            }]}/>

            <div className={style.agreeContent}>
                <img src={this.state.agree ? "./images/checked.png" : "./images/noChecked.png"} onClick={() => {
                    this.setAgreeStatus()
                }}/>
                <span>已阅读并同意</span>
                <Link to="agreement">《驾驶证邮寄服务协议》</Link>
            </div>

            <div className={style.buttonGroup}>
                <button className={style.submitButton}
                        onClick={() => {
                            //等待所有更新操作完成之后才提交，防止验证出错
                            setTimeout(() => {
                                this.submitData()
                            }, 0);
                        }}>
                    立即办理
                </button>
            </div>
            <div className={style.owerTips}>本服务由中国邮政速递物流提供</div>
            {/*底部导航菜单start*/}
            <BottomMenu onChange={(index) => {
                this.bottomHandle(index);
            }} data={[{
                text: '驾驶证邮寄',
                img: './images/licenceCard.png',
                checkedImg: './images/licenceCard_checked.png'
            }, {text: '我的订单', img: './images/my.png', checkedImg: './images/my_checked.png'}]}/>
            {/*底部导航菜单end*/}
        </div>
    }
}

//使用context
Home.contextTypes = {
    router: React.PropTypes.object.isRequired
};


function mapStateToProps(state) {
    return Object.assign({}, state.homeInfo, state.currentAddress);
}

export default connect(mapStateToProps)(Home);

